const mongoose = require('mongoose')
mongoose.set('useFindAndModify', false);
const Schemas = require('../models/index')

const Word = mongoose.model('Word', Schemas.Word)

const WordAPI = {
  undercover: () => {
    return new Promise((resolve) => {
      Word.find({ type: '谁是卧底' }).exec(function(err, docs) {
        if(err) {
          resolve({
            code: 500,
            message: err
          })
        } else {
          resolve({
            code: 200,
            message: 'success',
            data: docs.reverse()
          })
        }
      })
    })
  },
  guess: () => {
    return new Promise((resolve) => {
      Word.find({ type: { $ne: '谁是卧底' } }).exec(function(err, docs) {
        if(err) {
          resolve({
            code: 500,
            message: err
          })
        } else {
          resolve({
            code: 200,
            message: 'success',
            data: docs.reverse()
          })
        }
      })
    })
  },
  list: (data) => { 
    return new Promise((resolve) => {
      Word.find(data).exec(function(err, docs) {
        if(err) {
          resolve({
            code: 500,
            message: err
          })
        } else {
          resolve({
            code: 200,
            message: 'success',
            data: docs.reverse()
          })
        }
      })
    })
  },
  insert: (data) => {
    let words = []
    for(let i=0;i<data.length;i++) {
      words.push(new Word(data[i]))
    }
    return new Promise((resolve) => {
      Word.insertMany(words, function(err, docs) {
        if(err) {
          resolve({
            code: 500,
            message: err
          })
        } else {
          resolve({
            code: 200,
            data: docs,
            message: '添加成功'
          })
        }
      })
    })
  },
  delete: (ids) => {
    return new Promise((resolve) => {
      Word.deleteMany({ _id: { $in: ids} }, function(err, docs) {
        if(err) {
          resolve({
            code: 500,
            message: err
          })
        } else {
          resolve({
            code: 200,
            data: docs,
            message: '删除成功'
          })
        }
      })
    })
  },
  update: (id, data) => {
    return new Promise((resolve, reject) => {
      Word.findOneAndUpdate({ _id: id} , data, function(err, docs) {
        if (err) {
          resolve({
            code: 500,
            message: err
          })
        } else {
          resolve({
            code: 200,
            message: '修改成功！',
            data: docs
          })
        }
      })
    })
  }
}

module.exports = WordAPI